﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Zinnia.Lite.Core.Imp
{
    /// <summary>
    /// XML序列化服务
    /// </summary>
    internal class XmlSerializerService : IXmlSerializerService
    {
        /// <summary>
        /// XML序列化对象
        /// </summary>
        private XmlSerializer _xmlSerializer = null;
        public XmlSerializerService(Type type)
        {
            _xmlSerializer = new XmlSerializer(type);
        }
        public object XmlDeserialize(string xml)
        {
            try
            {
                using (StringReader stringReader = new StringReader(xml))
                {
                    return _xmlSerializer.Deserialize(stringReader);
                }
            }
            catch (Exception innerException)
            {
                bool flag = (xml != null) && (xml.StartsWith(Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble())));
                throw new ApplicationException(string.Format("Couldn't parse XML: '{0}'; Contains BOM: {1}; .", xml, flag), innerException);
            }
        }

        public string XmlSerialize(object obj)
        {
            string result = null;
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false)) { Formatting = Formatting.Indented };
                    _xmlSerializer.Serialize(xmlTextWriter, obj);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                    result = uTF8Encoding.GetString(memoryStream.ToArray());
                }
            }
            catch (Exception innerException)
            {
                throw new ApplicationException("Couldn't Serialize Object:" + obj.GetType().Name, innerException);
            }
            return result;
        }
    }
}
